import { ref, onMounted } from 'vue';
import { apiService, type DataItem } from '@/services/api-service';
import { ElMessage } from 'element-plus';

export function useApi() {
  const loading = ref(false);
  const error = ref<string | null>(null);
  const data = ref<DataItem[]>([]);
  const status = ref<{ status: string; timestamp: number } | null>(null);

  const fetchData = async (params?: Record<string, any>) => {
    loading.value = true;
    error.value = null;

    try {
      const response = await apiService.getData(params);
      if (response.success && response.data) {
        data.value = response.data;
      } else {
        error.value = response.error || response.message || '获取数据失败';
        ElMessage.error(error.value);
      }
    } catch (err) {
      error.value = '网络请求失败';
      ElMessage.error(error.value);
    } finally {
      loading.value = false;
    }
  };

  const postData = async (newData: Omit<DataItem, 'id'>) => {
    loading.value = true;
    error.value = null;

    try {
      const response = await apiService.postData(newData);
      if (response.success && response.data) {
        data.value.push(response.data);
        ElMessage.success('数据保存成功');
        return response.data;
      } else {
        error.value = response.error || response.message || '保存数据失败';
        ElMessage.error(error.value);
        return null;
      }
    } catch (err) {
      error.value = '网络请求失败';
      ElMessage.error(error.value);
      return null;
    } finally {
      loading.value = false;
    }
  };

  const updateData = async (id: string, updateData: Partial<DataItem>) => {
    loading.value = true;
    error.value = null;

    try {
      const response = await apiService.updateData(id, updateData);
      if (response.success && response.data) {
        const index = data.value.findIndex((item) => item.id === id);
        if (index !== -1) {
          data.value[index] = response.data;
        }
        ElMessage.success('数据更新成功');
        return response.data;
      } else {
        error.value = response.error || response.message || '更新数据失败';
        ElMessage.error(error.value);
        return null;
      }
    } catch (err) {
      error.value = '网络请求失败';
      ElMessage.error(error.value);
      return null;
    } finally {
      loading.value = false;
    }
  };

  const deleteData = async (id: string) => {
    loading.value = true;
    error.value = null;

    try {
      const response = await apiService.deleteData(id);
      if (response.success) {
        data.value = data.value.filter((item) => item.id !== id);
        ElMessage.success('数据删除成功');
        return true;
      } else {
        error.value = response.error || response.message || '删除数据失败';
        ElMessage.error(error.value);
        return false;
      }
    } catch (err) {
      error.value = '网络请求失败';
      ElMessage.error(error.value);
      return false;
    } finally {
      loading.value = false;
    }
  };

  const getStatus = async () => {
    try {
      const response = await apiService.getStatus();
      if (response.success && response.data) {
        status.value = response.data;
        return response.data;
      } else {
        console.error('获取状态失败:', response.error || response.message);
        return null;
      }
    } catch (err) {
      console.error('获取状态失败:', err);
      return null;
    }
  };

  // 定时获取状态（可选）
  const startStatusPolling = (interval = 5000) => {
    const timer = setInterval(async () => {
      await getStatus();
    }, interval);

    return () => clearInterval(timer);
  };

  return {
    loading,
    error,
    data,
    status,
    fetchData,
    postData,
    updateData,
    deleteData,
    getStatus,
    startStatusPolling
  };
}
